package com.base.common.advice;

import com.base.common.enums.*;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.*;
import com.base.common.utils.EasyUtil;
import com.base.common.utils.PushUtils;
import com.opensymphony.xwork2.ActionContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * 工单提交方法的aop切面
 * 
 * @author Kevin Colin
 * 
 */

@Aspect
@Component
public class AspectAdvice {

    @Resource
    private UserMapper userMapper;
	@Resource
	private CompoundsMapper compoundsMapper;

	@Resource
	private EasyUtil easyUtil;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Resource
	private EmployeeMapper employeeMapper;

	@Resource
	private SmsMapper smsMapper;

	@Resource
	private SmsReportMapper smsReportMapper;
	
	@Resource
	private TerminalMapper terminalMapper;
	
	@Resource
	private TicketMapper ticketMapper;

	@Resource
	private TicketReportMapper ticketReportMapper;

	/**
	 * @param sTicket
	 * @param employee
	 */
	public void addReport(Ticket sTicket, Employee employee, int reportStatus,
			int reportCategories) {
		TicketReport ticketReport = new TicketReport();
		ticketReport.setStartTime(new Date());
		ticketReport.setEmployee(new Employee().setId(employee.getId()));
		ticketReport.setTicket(new Ticket().setId(sTicket.getId()));
		ticketReport.setCategories(reportCategories);
		ticketReport.setStatus(reportStatus);
		ticketReportMapper.addTicketReport(ticketReport);
	}

	@Transactional
	@AfterReturning(value = "subYGJTicketMethod()", returning = "result")
	public void doAfterEmployeeSub(JoinPoint jp, String result) {
		System.out.println("进入aop");

		// 获取session, 查找物业信息
//		Map<String, Object> session = ActionContext.getContext().getSession();
//		List<Employee> employees = (List<Employee>) session.get("users");
		// 获取报修物业信息
		Ticket ticket = (Ticket) jp.getArgs()[0];
		Compounds compounds = compoundsMapper.queryCompoundsById(ticket.getCompounds().getId()).get(0);
		

		// 查询工单ID
		Ticket sTicket = ticketMapper.queryTicketByCode(result); 

 		// 查询员工ID
		Employee employee = employeeMapper.queryEmployeeByPhone(
				compounds.getManagerPhone()).get(0);

		// 插入工单记录
		addReport(sTicket, employee, TicketReportStatus.UNTREATED.getValue(),
				TicketReportCategories.DISPATCH.getValue());

		

		// 给员工app发送通知
		List<Terminal> terminals = terminalMapper.queryTerminalById(employee
				.getTerminal().getId());
		String appleClientId = null;
		String androidClientId = null;
		/*if (terminals.size() > 0) {
			if (terminals.get(0).getAppleClientId() != null) {
				appleClientId = terminals.get(0).getAppleClientId();
				Sms sms = easyUtil.addSms(SmsCategories.STSTEMNOTIFIER
						.getValue(), SmsCategories.STSTEMNOTIFIER.getName(),
						"有新的订单需要您处理，订单号为" + result, employees.get(0)
						.getCompounds().getManagerPhone(), employee.getId(), 0);
				try {
					System.out.println(PushUtils.pushtoSingle(appleClientId,
							JsonUtil.dto2String(sms), AppType.YGJ.getValue()));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (terminals.get(0).getAndroidClientId() != null) {

				androidClientId = terminals.get(0).getAndroidClientId();
				Sms sms = easyUtil.addSms(SmsCategories.STSTEMNOTIFIER
						.getValue(), SmsCategories.STSTEMNOTIFIER.getName(),
						"有新的订单需要您处理，订单号为" + result, employees.get(0)
						.getCompounds().getManagerPhone(), employee.getId(), 0);
				try {
					System.out.println(PushUtils.pushtoSingle(androidClientId,
							JsonUtil.dto2String(sms), AppType.YGJ.getValue()));
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}*/
		String mess = null;
		if (terminals.size() > 0) {
			mess = "有新的工单需要您处理，工单号为" + result;
//			sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
//			int employeeCompounds = employeeCompoundsMapper.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employee.getId(), compounds.getId());
			if (terminals.get(0).getAppleClientId() != null) {
				appleClientId = terminals.get(0).getAppleClientId();
				sendSms(mess, compounds.getManagerPhone(), appleClientId, 
						AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
				easyUtil.sendSms(mess, compounds.getManagerPhone());
			}

			if (terminals.get(0).getAndroidClientId() != null) {
				androidClientId = terminals.get(0).getAndroidClientId();
				sendSms(mess, compounds.getManagerPhone(), androidClientId, 
						AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
//				sendSms(mess, compounds.getManagerPhone(), 0, employee.getId(), androidClientId, AppType.YGJ.getValue());
				easyUtil.sendSms(mess, compounds.getManagerPhone());
			}
		}
	}

	@Transactional
	@AfterReturning(value = "subTicketMethod()", returning = "result")
	public void doAfterSub(JoinPoint jp, String result) {
		try {
			System.out.println("进入aop");

			// 获取报修物业id
			Ticket ticket = (Ticket) jp.getArgs()[0];
			int userId = ticket.getUser().getId();

			// 获取session, 查找物业信息
			Map<String, Object> session = ActionContext.getContext().getSession();
			/*List<User> users = (List<User>) session.get("users");
			User user = null;
			for (int i = 0; i < users.size(); i++) {
				if (users.get(i).getId() == userId) {
					user = users.get(i);
					break;
				}
			}*/
            User user = userMapper.queryUserById(userId).get(0);
            Compounds compounds= compoundsMapper.queryCompoundsById(user.getCompounds().getId()).get(0);

            // 查询员工ID
			Employee employee = employeeMapper.queryEmployeeByPhone(
                    compounds.getManagerPhone()).get(0);

			int employeeCompounds = employeeCompoundsMapper.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employee.getId(), user.getCompounds().getId());

            // 查询工单ID
            Ticket sTicket = ticketMapper.queryTicketByCode(result);

			ticketMapper.updateEmployeeCompoundsByTicketId(employeeCompounds, sTicket.getId());

            // 插入工单记录
            addReport(sTicket, employee, TicketReportStatus.UNTREATED.getValue(),
                    TicketReportCategories.DISPATCH.getValue());

            // 判断是否是临时工单，如果是临时工单转换成报修工单
            /*if (ticket.getCategories() == TicketCategories.TEMPORARY.getValue()) {
                ticketMapper.updateCategoriesById(sTicket.getId(),
                        TicketCategories.REPAIR.getValue());
				*//*List<Ticket> tickets = ticketMapper
						.queryLastCodeByCategories(TicketCategories.TEMPORARY
								.getValue());*//*
                String code = "";
                DecimalFormat df = new DecimalFormat("000000");
                if (sTicket != null) {
                    String lastedCode = sTicket.getCode();
                    code = df.format(Integer.parseInt(lastedCode.substring(1)
                            .trim()));
                }
                code = TicketCategories.REPAIR.getName() + code;
                ticketMapper.updateCodeById(sTicket.getId(), code);
                result = code;
            }*/

			// 给业主app发送通知
			List<Terminal> terminalList = terminalMapper
					.queryTerminalByPhoneRegisted(ticket.getSubUserPhone(),
							AppType.CJY.getValue());
			String cappleClientId = null;
			String candroidClientId = null;
			String mess = null;
			if (terminalList.size() > 0) {
				mess = "尊敬的业主您好，您的工单已受理，工单号为" + result;
				if (terminalList.get(0).getAppleClientId() != null
						&& !"".equals(terminalList.get(0).getAppleClientId().trim())) {
					cappleClientId = terminalList.get(0).getAppleClientId();
//					sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
					sendSms(mess, ticket.getSubUserPhone(), cappleClientId,
							AppType.CJY.getValue(), SmsType.MAIN.getValue(), 0, terminalList.get(0).getId(), 0);
				}

				if (terminalList.get(0).getAndroidClientId() != null
						&& !"".equals(terminalList.get(0).getAndroidClientId()
								.trim())) {
					candroidClientId = terminalList.get(0).getAndroidClientId();
					sendSms(mess, ticket.getSubUserPhone(), candroidClientId,
							AppType.CJY.getValue(),  SmsType.MAIN.getValue(), 0, terminalList.get(0).getId(), 0);
				}
			}


			// 给项目经理发送短信
			easyUtil.sendSms("有新的工单需要您处理，工单号为" + result, compounds
					.getManagerPhone());

			// 给员工app发送通知
			List<Terminal> terminals = terminalMapper.queryTerminalById(employee
					.getTerminal().getId());
			String appleClientId = null;
			String androidClientId = null;
			if (terminals.size() > 0) {
				mess = "有新的工单需要您处理，工单号为" + result;
				if (terminals.get(0).getAppleClientId() != null) {
					appleClientId = terminals.get(0).getAppleClientId();
//					sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
					sendSms(mess, compounds
							.getManagerPhone(), appleClientId, 
							AppType.YGJ.getValue(),  SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
				}

				if (terminals.get(0).getAndroidClientId() != null) {
					androidClientId = terminals.get(0).getAndroidClientId();
					sendSms(mess, compounds
							.getManagerPhone(), androidClientId, 
							AppType.YGJ.getValue(),  SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
				}
			}


		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 
	 * @param mess
	 * @param phone
	 * @param clientId
	 * @param appType
	 * @param type
	 * @param smsId
	 * @param senderTerminalId
	 */
	public void sendSms(String mess, String phone, 
			String clientId, int appType, int type, int smsId, int receiveTerminalId, int senderTerminalId) {
		Sms sms = easyUtil.addSms(
				SmsCategories.STSTEMNOTIFIER.getValue(),
				SmsCategories.STSTEMNOTIFIER.getName(),
				mess, 
				phone, type, smsId, receiveTerminalId, senderTerminalId);

		try {
			System.out.println(PushUtils.pushtoSingle(clientId,
					JsonUtil.dto2String(sms), appType));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Pointcut("execution(* com.cjy.userReport.service.*.impl.*.sub*(..))")
	public void subTicketMethod() {
	}

	@Pointcut("execution(* com.ygj.employeeReport.service.*.impl.*.sub*(..))")
	public void subYGJTicketMethod() {
	}
}
